<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="type" @tab-click="handleClick">
      <!-- tab 1：图片  -->
      <el-tab-pane name="image">
        <span slot="label"><i class="el-icon-picture"></i> 图片</span>
        <div class="add_but" v-hasPermi="['mp:material:edit']">
          <el-upload :action="actionUrl" :headers="headers" multiple :limit="1" :file-list="fileList" :data="uploadData"
                     :before-upload="beforeImageUpload" :on-success="handleUploadSuccess">
            <el-button size="mini" type="primary">点击上传</el-button>
            <span slot="tip" class="el-upload__tip" style="margin-left: 5px">支持 bmp/png/jpeg/jpg/gif 格式，大小不超过 2M</span>
          </el-upload>
        </div>
        <div class="waterfall" v-loading="loading">
          <div class="waterfall-item" v-for="item in list" :key='item.id'>
            <a target="_blank" :href="item.url">
              <img class="material-img" :src="item.url">
              <div class="item-name">{{item.name}}</div>
            </a>
            <div class="item-media-id">
              <span>{{item.mediaId}}</span>
              <el-button 
                size="mini" 
                icon="el-icon-document-copy" 
                @click="copyMediaId(item.mediaId)"
                circle
              />
            </div>
            <el-row class="ope-row">
              <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(item)"
                         v-hasPermi="['mp:material:edit']"/>
            </el-row>
          </div>
        </div>
        <!-- 分页组件 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </el-tab-pane>

      <!-- tab 2：语音  -->
      <el-tab-pane name="voice"></el-tab-pane>

      <!-- tab 3：视频 -->
      <el-tab-pane name="video"></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { getMaterialPage, deletePermanentMaterial } from "@/api/mp/material";
import { getToken } from '@/utils/auth'

export default {
  name: 'MpMaterial',
  components: {
  },
  data() {
    return {
      type: 'image',
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据列表
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        permanent: 1,
      },

      actionUrl: process.env.VUE_APP_BASE_API  + '/mp/material/upload-permanent',
      headers: { Authorization: "Bearer " + getToken() },// 设置上传的请求头部
      fileList:[],
      uploadData: {
        "type": 'image',
        "title":'',
        "introduction":''
      },
      // === 视频上传，独有变量 ===
      dialogVideoVisible: false,
      addMaterialLoading: false,
      uploadRules: { // 视频上传的校验规则
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入描述', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getList();
  },
  methods: {
    // ======================== 列表查询 ========================
    /** 查询列表 */
    getList() {
      this.loading = true
      getMaterialPage({
        ...this.queryParams,
        type: this.type
      }).then(response => {
        this.list = response.rows
        this.total = response.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleClick(tab, event) {
      // 设置 type
      this.uploadData.type = tab.name
      // 从第一页开始查询
      this.handleQuery();
    },

    // ======================== 文件上传 ========================
    beforeImageUpload(file) {
      const isType = file.type === 'image/jpeg'
          || file.type === 'image/png'
          || file.type === 'image/gif'
          || file.type === 'image/bmp'
          || file.type === 'image/jpg';
      if (!isType) {
        this.$message.error('上传图片格式不对!')
        return false;
      }
      const isLt = file.size / 1024 / 1024 < 2
      if (!isLt) {
        this.$message.error('上传图片大小不能超过 2M!')
        return false;
      }
      this.loading = true
      return true;
    },
    beforeVoiceUpload(file){
      const isType = file.type === 'audio/mp3'
          || file.type === 'audio/mpeg'
          || file.type === 'audio/wma'
          || file.type === 'audio/wav'
          || file.type === 'audio/amr';
      const isLt = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传语音格式不对!')
        return false;
      }
      if (!isLt) {
        this.$message.error('上传语音大小不能超过 2M!')
        return false;
      }
      this.loading = true
      return true;
    },
    beforeVideoUpload(file){
      const isType = file.type === 'video/mp4'
      if (!isType) {
        this.$message.error('上传视频格式不对!')
        return false;
      }
      const isLt = file.size / 1024 / 1024 < 10
      if (!isLt) {
        this.$message.error('上传视频大小不能超过 10M!')
        return false
      }
      this.addMaterialLoading = true
      return  true
    },
    handleUploadSuccess(response, file, fileList) {
      this.loading = false
      this.addMaterialLoading = false
      if (response.code !== 200) {
        this.$message.error('上传出错：' + response.msg)
        return false;
      }

      // 清空上传时的各种数据
      this.dialogVideoVisible = false
      this.fileList = []
      this.uploadData.title = ''
      this.uploadData.introduction = ''

      // 加载数据
      this.getList()
    },
    // 下载文件
    handleDownload(row) {
      window.open(row.url,'_blank')
    },
    // 提交 video 新建的表单
    submitVideo() {
      this.$refs['uploadForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.$refs.uploadVideo.submit()
      })
    },
    handleAddVideo() {
      this.resetVideo();
      this.dialogVideoVisible = true
    },
    /** 取消按钮 */
    cancelVideo() {
      this.dialogVideoVisible = false;
      this.resetVideo();
    },
    /** 表单重置 */
    resetVideo() {
      this.fileList = []
      this.uploadData.title = ''
      this.uploadData.introduction = ''
      this.resetForm("uploadForm");
    },

    // ======================== 其它操作 ========================
    handleDelete(item) {
      const id = item.id
      this.$modal.confirm('此操作将永久删除该文件, 是否继续?').then(function() {
        return deletePermanentMaterial(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    copyMediaId(mediaId) {
    // 创建临时textarea元素
    const textarea = document.createElement('textarea')
    textarea.value = mediaId
    document.body.appendChild(textarea)
    textarea.select()
    
    try {
      // 执行复制命令
      const successful = document.execCommand('copy')
      if (successful) {
        this.$message.success('已复制 mediaId')
      } else {
        this.$message.error('复制失败，请手动复制')
      }
    } catch (err) {
      this.$message.error('复制失败: ' + err)
    }
    
    // 移除临时元素
    document.body.removeChild(textarea)
  },
  }
}
</script>

<style lang="scss" scoped>
/*瀑布流样式*/
.waterfall {
  width: 100%;
  column-gap: 15px;
  column-count: 5;
  margin-top: 10px;
}
.waterfall-item {
  padding: 10px;
  margin-bottom: 15px;
  break-inside: avoid;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
.material-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
}
.item-name {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ope-row {
  margin-top: 8px;
  text-align: center;
}
p {
  line-height: 30px;
}
@media (min-width: 992px) and (max-width: 1300px) {
  .waterfall {
    column-count: 3;
  }
  p {
    color:red;
  }
}
@media (min-width: 768px) and (max-width: 991px) {
  .waterfall {
    column-count: 2;
  }
  p {
    color: orange;
  }
}
@media (max-width: 767px) {
  .waterfall {
    column-count: 1;
  }
}
/*瀑布流样式*/
.item-media-id {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 6px;
  padding: 4px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
  
  span {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .el-button {
    margin-left: 8px;
    padding: 4px;
  }
}
</style>
